import { IAssemblyDocTreeNode, IAssemblyConstraint } from '@amcax/base';
import { allParts } from '@app-cad/pages/product-support/part-funcs';
import { isEmpty } from 'lodash';

// 得到零件的一级节点
export const get1stLevelPartFromId = (id: string) => {
  let part = allParts.get(id?.split(':')?.[0] || '');
  if (!part) {
    return null;
  }

  let parent = part;
  while (parent.parent) {
    part = parent;
    parent = parent.parent;
  }

  return part;
};

export const getAllConstraints = (docTree: IAssemblyDocTreeNode) => {
  return docTree?.children?.find(
    (item) => item.type === 'assembly-constraints-root',
  )?.children;
};

export const getParamsId = (id: string, obj: any) => {
  if (obj?.objInfo?.type === 'Part::Sphere') {
    return id + ':f0';
  }
  return id;
};

export const getKeyConstraintArr = (docTree: any, key: string) => {
  if (isEmpty(docTree)) {
    return [];
  }
  if (key === '') {
    return [];
  }
  const allconstraints = getAllConstraints(docTree);
  const constraintArr = allconstraints?.filter(
    (constraint) =>
      (constraint?.originalObj as IAssemblyConstraint)?.item?.split(':')[0] ===
        key ||
      (constraint?.originalObj as IAssemblyConstraint)?.target?.split(
        ':',
      )[0] === key,
  );
  return constraintArr;
};

export const getAssembleNodesByIds = (
  ids: string[],
  parentNode: IAssemblyDocTreeNode,
) => {
  const result: IAssemblyDocTreeNode[] = [];
  if (ids.includes(parentNode.key)) {
    result.push(parentNode);
  }

  if (ids.length === result.length) {
    return result;
  }

  parentNode.children?.forEach((c) => {
    result.push(...getAssembleNodesByIds(ids, c));
  });

  return result;
};

export const getInvertNode = (keys: string | string[], docTree: any) => {
  const parts = docTree.children.filter((item) => item.type === 'part');
  if (Array.isArray(keys)) {
    return parts.filter((item) => !keys.includes(item.key));
  } else {
    return parts.filter((item) => item.key !== keys);
  }
};

export interface TreeNode {
  key: string;
  children?: TreeNode[];
}

export const getDescendantKeys = <T extends TreeNode = TreeNode>(
  node: T,
): string[] => {
  if (!node.children || node.children.length === 0) {
    return [];
  }
  return node.children.reduce(
    (keys, child) => [...keys, child.key, ...getDescendantKeys(child)],
    [] as string[],
  );
};
